const crypto = require('crypto')
let vertoken = require("../utils/token")

const { AuthErrStatus, CommonErrStatus } = require('../utils/error')
const { RespError, RespSuccess, RespData } = require('../utils/resp')
const { Query } = require('../utils/query')
class AppServices {
  // 产品分类列表
  async classifyList (ctx, next) {
    let { query } = ctx.request
    try {
      let sql = ''
      let sqlTotal = ''
      sql = `SELECT
          product_classify.*
        FROM
          product_classify
        WHERE
          product_classify.status = 0
        ORDER BY
          product_classify.create_time ASC
        LIMIT ${(query.pageNum - 1) * query.pageSize},${query.pageSize}; `
      sqlTotal = `SELECT COUNT(*) FROM product_classify; `
      const results = await Query(sql, [])
      let total = (await Query(sqlTotal))[0]['COUNT(*)']
      let data = {
        rows: results,
        total: total
      }
      return RespData(ctx, data)
    } catch {
      return RespError(ctx, CommonErrStatus.SERVER_ERR)
    }
  }

  // 产品列表
  async libraryList (ctx, next) {
    let { query } = ctx.request
    try {
      let sql = ''
      let sqlTotal = ''
      let count = ''
      if (query.classifyId) {
        sql = `SELECT
            product_library.*
          FROM
            product_library
          WHERE
            product_library.status = 0
          HAVING
            product_library.classify_id = ?
          ORDER BY
            product_library.create_time ASC LIMIT ${(query.pageNum - 1) * query.pageSize},${query.pageSize}; `
        sqlTotal = `SELECT
            COUNT(classify_id)
          FROM
            product_library
          WHERE
            classify_id = ${query.classifyId}; `
        count = 'COUNT(classifyId)'
      } else {
        sql = `SELECT
            product_library.*
          FROM
            product_library
          ORDER BY
            product_library.create_time ASC LIMIT ${(query.pageNum - 1) * query.pageSize},${query.pageSize}; `
        sqlTotal = `SELECT
            COUNT(*)
          FROM
            product_library;`
        count = 'COUNT(*)'
      }
      const results = await Query(sql, [query.classifyId])
      let total = (await Query(sqlTotal))[0][count]
      let data = {
        rows: results,
        total: total
      }
      return RespData(ctx, data)
    } catch {
      return RespError(ctx, CommonErrStatus.SERVER_ERR)
    }
  }
  // 产品详情
  async libraryDetailsById (ctx, next) {
    let { query } = ctx.request
    try {
      let sql = `
        SELECT 
          product_library.*
        FROM
          product_library
        WHERE
          product_library.library_id = ?`
      const results = await Query(sql, [query.libraryId])
      let obj = {
        data: results[0],
      }
      return RespData(ctx, obj)
    } catch {
      return RespError(ctx, CommonErrStatus.SERVER_ERR)
    }
  }
}

module.exports = new AppServices()